package com.xiaoc.bulldozer.controller;

import com.xc.framework.web.CookieUtils;
import com.xiaoc.bulldozer.common.Constant;
import com.xiaoc.bulldozer.common.dto.LoginUserDto;
import com.xiaoc.bulldozer.common.model.User;
import com.xiaoc.bulldozer.common.service.UserService;
import com.xiaoc.bulldozer.common.util.SecurityUtils;
import com.xiaoc.bulldozer.facade.UserFacade;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController extends AdminBaseController {

    @Resource(name = "userFacade")
    private UserFacade userFacade;

    @Resource(name = "userService")
    private UserService userService;

    @RequestMapping(value = "/gotoLogin", method = RequestMethod.GET)
    public ModelAndView gotoLogin(String redirectUrl) {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("redirectUrl", redirectUrl);
        return renderHtml("user/login.html", paramMap);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(HttpServletResponse response, String loginName, String password, String redirectUrl) {

        // 若参数为空则直接跳转至登陆页面
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("loginName", loginName);
        paramMap.put("redirectUrl", redirectUrl);
        if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
            return renderHtml("user/login.html", paramMap);
        }

        // 验证用户名和密码
        User user = userService.getUserByLoginName(loginName);
        if (user == null || !user.getLoginPwd().equals(SecurityUtils.generatePassword(password))) {
            paramMap.put("errorMsg", "账号密码不匹配");
            return renderHtml("user/login.html", paramMap);
        }

        // 锁定状态判断
        if (User.STATUS_LOCK.equals(user.getEnableStatus())) {
            paramMap.put("errorMsg", "账号" + loginName + "已被锁定，无法登陆");
            return renderHtml("user/login.html", paramMap);
        }

        // 登陆用户
        LoginUserDto loginUserDto = new LoginUserDto();
        BeanUtils.copyProperties(user, loginUserDto);
        loginUserDto.setLoginTime(System.currentTimeMillis());
        userFacade.login(loginUserDto);
        CookieUtils.setCookie(getRequest(), response, Constant.COOKIE_SESSION_ID, loginUserDto.getSessionId());

        // 默认跳转到权重最高的菜单页
        return redirect(getRequest().getContextPath() + "/");
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {

        LoginUserDto loginUserDto = getCurrentLoginUser(request, response);
        userFacade.logout(loginUserDto.getSessionId());

        return redirect(getRequest().getContextPath() + "/gotoLogin");
    }

    @RequestMapping(value = "/gotoProxyLogin", method = RequestMethod.GET)
    public ModelAndView gotoProxyLogin() {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        return renderHtml("user/proxy_login.html", paramMap);
    }

    /**
     * 代理登陆
     * 
     * @param loginName
     *            被代理用户名
     * @param password
     *            代理用户密码
     * @param proxyLoginName
     *            代理用户名
     */
    @RequestMapping(value = "/proxyLogin", method = RequestMethod.POST)
    public ModelAndView proxyLogin(HttpServletResponse response, String loginName, String proxyLoginName, String password) {

        // 若参数为空则直接跳转至登陆页面
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("loginName", loginName);
        paramMap.put("proxyLoginName", proxyLoginName);
        if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password) || StringUtils.isBlank(proxyLoginName)) {
            return renderHtml("user/proxy_login.html", paramMap);
        }

        // 当代理账号和被代理账号相同时跳转到login函数
        if (loginName.equals(proxyLoginName)) {
            paramMap.put("errorMsg", "请不要代理自己");
            return renderHtml("user/proxy_login.html", paramMap);
        }

        // 只允许列表中的人代理登录
        if (!"admin|yangzhen|liuchun||xiaoman".contains(proxyLoginName)) {
            paramMap.put("errorMsg", "您没有代理登录权限");
            return renderHtml("user/proxy_login.html", paramMap);
        }

        // 验证用户名和密码
        User proxyUser = userService.getUserByLoginName(proxyLoginName);
        if (proxyUser == null || !proxyUser.getLoginPwd().equals(SecurityUtils.generatePassword(password))) {
            paramMap.put("errorMsg", "账号密码不匹配");
            return renderHtml("user/proxy_login.html", paramMap);
        }

        // 验证被代理用户
        User realUser = userService.getUserByLoginName(loginName);
        if (realUser == null || !realUser.isEnable()) {
            paramMap.put("errorMsg", "用户不存在");
            return renderHtml("user/proxy_login.html", paramMap);
        }

        // 锁定状态判断
        if (User.STATUS_LOCK.equals(realUser.getEnableStatus())) {
            paramMap.put("errorMsg", "账号" + loginName + "已被锁定，无法登陆");
            return renderHtml("user/proxy_login.html", paramMap);
        }

        // 不允许代理超级管理员和空间管理员
        if (!"admin,yangzhen,liuchun,xiaoman".contains(proxyLoginName)) {
            paramMap.put("errorMsg", "系统异常A");
            return renderHtml("user/proxy_login.html", paramMap);
        }

        LoginUserDto loginUserDto = new LoginUserDto();
        BeanUtils.copyProperties(realUser, loginUserDto);
        loginUserDto.setProxyLoginName(proxyLoginName);
        loginUserDto.setLoginTime(System.currentTimeMillis());
        userFacade.login(loginUserDto);
        CookieUtils.setCookie(getRequest(), response, Constant.COOKIE_SESSION_ID, loginUserDto.getSessionId());

        // 默认跳转到权重最高的菜单页
        return redirect(getRequest().getContextPath() + "/");
    }
}
